﻿using Microsoft.Extensions.DependencyInjection;
using System;

namespace DependencyInjection.Core
{
    /// <summary>
    /// 依赖注入 接口 --- 反射 --- 依赖注入 --- 插件
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            //媳妇儿开车出去玩
            var driver = new Driver(new Car());
            driver.Run();
            //媳妇儿又买了一辆JEEP车去兜风了
            driver = new Driver(new JeepCar());
            driver.Run();

            //撞车了，把新买的车都给撞坏了，然后我决定给她买辆坦克
            driver = new Driver(new Tank());
            driver.Run();
            IWeapon tank = new Tank();
            tank.Fire();

            {
                //通过反射方式让媳妇儿开上车
                Console.WriteLine("*********************************************");
                Console.WriteLine("*****************通过反射方法让车跑起来****************************");
                var tank1 = Activator.CreateInstance(typeof(Tank));
                //var runMethod = Type.GetType("DependencyInjection.Core.Tank").GetMethod("Run");
                var runMethod = tank.GetType().GetMethod("Run");
                runMethod.Invoke(tank1,null);

            }

            {
                //依赖注入，利用.netCore 的依赖注入框架完成
                /**0.Nuget安装DependencyInjection
                 * 1.容器的概念，一般命名为ServiceProvider 
                 * 2.所有的实例都由容器来管理
                 * 3.依赖注入借助 接口/反射来实现。
                 * **/

                var serviceCellection = new ServiceCollection();
                serviceCellection.AddScoped(typeof(IVehicle), typeof(Car));
                serviceCellection.AddScoped(typeof(Driver));
                var sp = serviceCellection.BuildServiceProvider();
                IVehicle myTank = sp.GetService<IVehicle>();
                myTank.Run();
                var newDriver = sp.GetService<Driver>();
                newDriver.Run();

            }
            Console.ReadKey();
        }
    }
}
